package com.company.ems.util;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import com.company.ems.mapper.UserMapper;
import com.company.ems.mapper.EmployeeMapper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 使用自定义数据源
            DataSource dataSource = new UnpooledDataSource() {
                @Override
                public Connection getConnection() throws SQLException {
                    return DatabaseConfig.getConnection();
                }

                @Override
                public Connection getConnection(String username, String password) throws SQLException {
                    return DatabaseConfig.getConnection();
                }
            };

            Environment environment = new Environment(
                    "development",
                    new JdbcTransactionFactory(),
                    dataSource
            );

            Configuration configuration = new Configuration(environment);
            configuration.addMapper(UserMapper.class);
            configuration.addMapper(EmployeeMapper.class);
            configuration.setMapUnderscoreToCamelCase(true);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

        } catch (Exception e) {
            throw new RuntimeException("MyBatis初始化失败", e);
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}